<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

class Subject extends Backend
{
    //当前对象的模型
    protected $model;

    //开启关联查询
    protected $relationSearch = true;

    //快速搜索时执行查找的字段
    protected $searchFields = 'id,title,category.name,teacher.name';

    public function __construct()
    {
        parent::__construct();

        $this->model = model('subject.Subject'); //model指向数据库路径

        //查询分类数据并组装
        $CateData = model('subject.Category')->order('weight desc')->column('id,name');

        //查询老师数据并组装
        $Teacher = model('subject.Teacher')->order('id desc')->column('id,name');

        $this->assign([
            'CateData' => $CateData,
            'Teacher' => $Teacher
        ]);
    }


    public function index()
    {
        if ($this->request->isAjax()) {
            //设置过滤方法
            $this->request->filter(['strip_tags', 'trim']);

            //如果发送的来源是 Selectpage，则转发到 Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            //通过fastadmin封装函数处理前端发过来的参数
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['category', 'teacher'])
                ->where($where)          //搜索条件
                ->order($sort, $order)         //$sort排序字段,$order降序还是升序
                ->paginate($limit);    //调用分页函数

            $result = ['total' => $list->total(), 'rows' => $list->items()];      //返回排序总数total()和排序数据items()
            return json($result);    //返回数据
        }

        return $this->fetch();
    }


    //添加
    public function add()
    {

        if ($this->request->isAjax()) {

            //接收row数组的参数，告诉应用接收数组，解析数组，“/a”强制转化为数组
            $params = $this->request->param('row/a');

            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));    //排除前端提交过来的字段
            }

            $result = $this->model->validate('common/subject/Subject')->save($params);

            if ($result === false) {

                is_file('.' . $params['thumbs']) && unlink('.' . $params['thumbs']);   //unlink删除相对路径或绝对路径下的文件，返回true或false
                $this->error($this->model->getError());
            } else {
                $this->success();
            }
        }
        return $this->fetch();
    }


    //编辑
    public function edit($ids = null)
    {
        $ids = $ids ?: $this->request->param('ids', 0, 'trim');    //课程id

        $row = $this->model->find($ids);

        if (!$row) {
            $this->error("课程不存在");
        }

        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');

            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));    //排除前端提交过来的字段
            }

            $params['id'] = $ids;    //追加主键id

            $result = $this->model->validate('common/subject/Subject')->isUpdate(true)->save($params);

            if ($result) {
                if ($row['thumbs'] != $params['thumbs']) {
                    is_file('.' . $row['thumbs']) && unlink('.' . $row['thumbs']);   //unlink删除相对路径或绝对路径下的文件，返回true或false
                }
                $this->success("更新成功");
            } else {
                if ($row['thumbs'] != $params['thumbs']) {
                    is_file('.' . $params['thumbs']) && unlink('.' . $params['thumbs']);   //unlink删除相对路径或绝对路径下的文件，返回true或false
                }
                $this->error($this->model->getError());
            }
        }

        $this->assign([
            'row' => $row
        ]);

        return $this->fetch();
    }


    //软删除 模型中使用了软删除
    public function del($ids = null)
    {
        $ids = $ids ?: $this->request->param("ids", '', 'trim');

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $list = $this->model->where(['id' => ['IN', $ids]])->select();

        if (empty($list)) {
            $this->error(__('No rows were deleted'));
        }

        //删除
        $result = $this->model->destroy($ids);

        if ($result === false) {
            $this->error();
        } else {
            $this->success();
        }
    }

    //回收站
    public function recyclebin()
    {
        if ($this->request->isAjax()) {
            //设置过滤方法
            $this->request->filter(['strip_tags', 'trim']);

            //如果发送的来源是 Selectpage，则转发到 Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            //通过fastadmin封装函数处理前端发过来的参数
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['category', 'teacher'])
                ->where($where)          //搜索条件
                ->order($sort, $order)         //$sort排序字段,$order降序还是升序
                ->paginate($limit);    //调用分页函数

            $result = ['total' => $list->total(), 'rows' => $list->items()];      //返回排序总数total()和排序数据items()
            return json($result);    //返回数据
        }
    }

    //还原
    public function restore($ids = null)
    {
        if ($this->request->isAjax()) {
            $ids = $ids ?: $this->request->param('ids', '', 'trim');

            if (empty($ids)) {
                $this->error(__('Parameter %s can not be empty', 'ids'));
            }

            $list = $this->model->onlyTrashed()->select($ids);

            if (!$list) {
                $this->error(__('No rows were deleted'));
            }

            $result = $this->model->onlyTrashed()->where('id', 'IN', $ids)->update(['deletetime' => null]);

            if ($result === false) {
                $this->error('还原失败');
            } else {
                $this->success();
            }
        }
    }


    //真正删除
    public function destroy($ids = null)
    {
        $ids = $ids ?: $this->request->param('ids', '', 'trim');

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $list = $this->model->onlyTrashed()->select($ids);

        if (!$list) {
            $this->error(__('No rows were deleted'));
        }

        // 把图片和章节的视频的资源也删除

        // 查询获取章节数据 array_keys
        $ChapterData = model('subject.Chapter')->where(['subid' => ['IN', $ids]])->select();

        $result = $this->model->destroy($ids, true);

        if ($result === false) {
            $this->error('真实删除失败');
        } else {

            // 课程封面图
            foreach ($list as $item) {
                @is_file('.' . $item['thumbs']) && unlink('.' . $item['thumbs']);
            }

            // 章节视频
            foreach ($ChapterData as $item) {
                @is_file('.' . $item['url']) && unlink('.' . $item['url']);
            }

            $this->success();
        }
    }
}
